package com.xiaohe66.web.application.im;

import com.xiaohe66.common.util.IdWorker;
import com.xiaohe66.common.web.sec.annotation.NeedRoleAll;
import com.xiaohe66.common.web.validator.annotation.Verify;
import com.xiaohe66.web.application.im.bo.ListUnreadMessageDigestBo;
import com.xiaohe66.web.application.im.bo.MessageAddBo;
import com.xiaohe66.web.application.im.bo.MessageListBo;
import com.xiaohe66.web.application.im.convert.MessageBoConverter;
import com.xiaohe66.web.application.im.result.MessageListUnreadDigestResult;
import com.xiaohe66.web.application.im.result.MessageResult;
import com.xiaohe66.web.domain.account.value.AccountId;
import com.xiaohe66.web.domain.im.agg.Message;
import com.xiaohe66.web.domain.im.repository.MessageRepository;
import com.xiaohe66.web.domain.im.service.MessageService;
import com.xiaohe66.web.domain.im.value.MessageContext;
import com.xiaohe66.web.domain.im.value.MessageId;
import com.xiaohe66.web.domain.im.value.MessageUnread;
import com.xiaohe66.web.domain.sys.sec.service.SecurityService;
import com.xiaohe66.web.domain.sys.sec.value.RoleName;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author xiaohe
 * @since 2023.08.10 13:41
 */
@Service
@RequiredArgsConstructor
public class MessageAppService {

    private final MessageBoConverter boConverter;
    private final SecurityService securityService;
    private final MessageRepository messageRepository;
    private final MessageService messageService;

    @Verify
    @NeedRoleAll(RoleName.IM_ROLE_VALUE)
    public void addMessage(MessageAddBo bo) {

        Message message = boConverter.newMessage(bo, IdWorker.genId());

        messageService.save(message);
    }

    @NeedRoleAll(RoleName.IM_ROLE_VALUE)
    public List<MessageListUnreadDigestResult> listUnreadMessageDigest(ListUnreadMessageDigestBo bo) {

        AccountId currentAccountId = securityService.getCurrentAccountId();

        List<MessageUnread> list = messageService.countByAccountIdUnread(currentAccountId);

        return boConverter.toUnreadResult(list);
    }

    @Verify
    @NeedRoleAll(RoleName.IM_ROLE_VALUE)
    public List<MessageResult> list(MessageListBo bo) {

        AccountId currentAccountId = securityService.getCurrentAccountId();

        AccountId createId = new AccountId(bo.getCreateId());

        List<Message> list = messageService.pageOfAccountId(bo.toPaging(), createId, currentAccountId);

        return boConverter.toResult(list);
    }
}
